<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorator="layout/tpl">
<head>
    <meta charset="UTF-8"/>
    <title>添加用户</title>
    <style>
        form {
            padding: 10px;
        }
    </style>
</head>
<body layout:fragment="content">
<form class="layui-form  layui-form-pane">


    <div class="layui-form-item">
        <label class="layui-form-label">菜品名称</label>
        <div class="layui-input-block">
            <input type="text" id="dish" name="dish" lay-verify="required" autocomplete="off" placeholder="请输入菜品名称" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">类型</label>
        <div class="layui-input-inline">
            <select id="category" name="category" lay-filter="s1" >
            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">库存</label>
        <div class="layui-input-block">
            <input type="text" id="stock" name="stock" autocomplete="off" lay-verify="required" placeholder="请输入库存数" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item" pane="">
        <label class="layui-form-label">是否可用</label>
        <div class="layui-input-block">
            <input type="checkbox" id="available" checked="" name="available" lay-skin="switch" lay-filter="available" lay-text="ON|OFF">
        </div>
    </div>

    <div class="layui-upload-drag" id="uploader" style="width: 88%">
        <i class="layui-icon"></i>
        <p>点击上传，或将文件拖拽到此处</p>
    </div>
    <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
        预览图：
        <div class="layui-upload-list" id="imglistCtn">
            <div class="layui-upload-list">
                <table class="layui-table" style="text-align: center;">
                    <thead>
                    <tr>
                        <th style="text-align: center;">图片预览</th>
                        <th style="text-align: center;">大小</th>
                        <th style="text-align: center;">状态</th>
                        <th style="text-align: center;">操作</th>
                    </tr>
                    </thead>
                    <tbody id="imgList"></tbody>
                </table>
            </div>
        </div>
    </blockquote>

    <button hidden id="sb" lay-submit="" lay-filter="sb"></button>
</form>
</body>
<script type="text/javascript" th:inline="javascript" layout:fragment="myscript">

    var available = true;
    layui.use(['form' , 'upload'], function(){
        var info = [[${info}]];
        var dishInfo = JSON.parse(info);
        console.log(dishInfo);
        $("#stock").val(dishInfo.stock);
        $("#dish").val(dishInfo.dish);
        $("#category").val(dishInfo.category);
        form = layui.form;
        upload = layui.upload;
        form.on('switch(available)' , function(data){
            available = data.elem.checked;
        });

        form.on('submit(sb)', function(data){
            var imgs = Object.values(uploadList).join(",");
            data.field.id = dishInfo.id;
            data.field.img_path = imgs;
            $.post("/menu/update" , data.field , function(ret){
                if (ret.code == 0) {
                    parent.layer.close(parent.updateIndex);
                    parent.productGrid.reload({
                        page: {
                            curr: 1 //重新从第 1 页开始
                        }
                    });
                }
            } , "json");
            return false;
        });


        var totalArray = new Array();
        var uploadList = {};
        //拖拽上传
        upload.render({
            elem: '#uploader'
            ,url: '/menu/saveImg' //改成您自己的上传接口
            ,accept: 'images'
            , choose: function (obj) {
                var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                var arr = Object.keys(files);
                totalArray = totalArray.concat(arr);
                // 检查上传文件的个数
                if (totalArray.length <= 6) {
                    //读取本地文件
                    obj.preview(function (index, file, result) {
                        var tr = $(['<tr id="upload-' + index + '">'
                            , '<td><img src="' + result + '" alt="' + file.name + '" class="layui-upload-img" style="height: 66px;width:100px;"></td>'
                            , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                            , '<td>等待上传</td>'
                            , '<td>'
                            , '<button class="layui-btn demo-reload layui-hide">重传</button>'
                            , '<button class="layui-btn layui-btn-danger demo-delete">删除</button>'
                            , '</td>'
                            , '</tr>'].join(''));
                        //单个重传
                        tr.find('.demo-reload').on('click', function () {
                            obj.upload(index, file);
                        });

                        //删除
                        tr.find('.demo-delete').on('click', function () {
                            delete files[index]; //删除对应的文件
                            delete uploadList[index];
                            tr.remove();
                            uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                        });

                        $('#imgList').append(tr);
                    });
                } else {
                    // 超出上传最大文件
                    layer.msg("上传文件最大不超过6个")
                }

            }
            ,done: function(res){
                uploadList[totalArray[totalArray.length - 1]] = res["fileName"];
                layer.msg('上传成功');
            }
            ,error: function(index, upload){
                //当上传失败时，你可以生成一个“重新上传”的按钮，点击该按钮时，执行 upload() 方法即可实现重新上传
            }
        });
        var imgs = dishInfo.img_path.split(',');
        for (var i = 0; i < imgs.length; i++) {
            uploadList[i] = imgs[i];
            var tr = $(['<tr id="upload-' + i + '">'
                , '<td><img src="' + '/getpic/'+imgs[i] + '" alt="" class="layui-upload-img" style="height: 66px;width:100px;"></td>'
                , '<td>-kb</td>'
                , '<td>已上传</td>'
                , '<td>'
                , '<button class="layui-btn demo-reload layui-hide"></button>'
                , '<button class="layui-btn layui-btn-danger demo-delete">删除</button>'
                , '</td>'
                , '</tr>'].join(''));


            $('#imgList').append(tr);
        }
        //删除
        $('.demo-delete').on('click', function () {
            var p = $(this).parent().parent();
            var index = p.attr("id");
            index = index.split('-')[1];
            delete uploadList[index];
            p.remove();
            return false;
        });
        $.post("/mainc/getOptions" , function (data) {
            var categorySelect = $("#category");
            var ts;
            categorySelect.append('<option value="">请选择类型</option>');
            for (var key in data) {
                ts = categorySelect.append('<optgroup label='+key+'></optgroup>');
                for (var i = 0 ; i < data[key].length ; i++) {
                    if (dishInfo["id"] == data[key][i]['id']) {
                        ts.append("<option checked='checked' value='"+data[key][i]['id']+"'>"+data[key][i]['cname']+"</option>");
                    } else {
                        ts.append("<option value='"+data[key][i]['id']+"'>"+data[key][i]['cname']+"</option>");
                    }


                }

            }
            form.render('select');
        } ,"json");

    });
</script>
</html>